package com.ling.module1sbbyyds.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ling.sbbyyds.entity.users.User;
import com.ling.module1sbbyyds.utils.UserThreadLocal;
import com.ling.sbbyyds.common.ToolKits;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * 天道酬勤、学无止境
 *
 * @Description: 登录拦截
 * @author: ling
 * @date: 2022年03月25日
 */
@Slf4j
@Component
public class UserInfoInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redis;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HashMap<String, Object> data = new HashMap<>();
        try {
            //获取请求中header的token
            String token = request.getHeader("AuthorizationOauth_Token");
            //获取到有token
            if (token != null) {
                //获取redis中是否有这个token   key:token  value: User(用户信息)
                String jsonUser = redis.opsForValue().get(token);
                //存在token，已登录
                if (jsonUser != null) {
                    //存用户信息
                    data.put("user", JSONObject.parseObject(jsonUser, User.class));
                }
            }
            data.put("ip", ToolKits.getRequestIp(request));
            UserThreadLocal.put(data);
        } catch (Exception e) {
            log.error("用户信息拦截器出现内部错误！");
            log.error("错误为：{}", e.toString());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除线程中用户信息
        UserThreadLocal.remove();
    }

}
